package com.blog.cmrpersonalblog.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.cmrpersonalblog.dto.homepage.HomePageQueryRequest;
import com.blog.cmrpersonalblog.dto.homepage.HomePageResponse;
import com.blog.cmrpersonalblog.entity.ArticleTag;
import com.blog.cmrpersonalblog.service.ArticleTagRelationService;
import com.blog.cmrpersonalblog.mapper.ArticleMapper;
import com.blog.cmrpersonalblog.mapper.CategoryMapper;
import com.blog.cmrpersonalblog.service.HomePageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户端首页服务实现类
 */
@Slf4j
@Service
public class HomePageServiceImpl implements HomePageService {

   @Resource
    private ArticleMapper articleMapper;

   @Resource
    private CategoryMapper categoryMapper;

   @Resource
    private ObjectMapper objectMapper;

   @Resource
    private ArticleTagRelationService articleTagRelationService;

    @Override
    public HomePageResponse getHomePageData(HomePageQueryRequest queryRequest) {
        log.info("获取首页数据: {}", queryRequest);

        HomePageResponse response = new HomePageResponse();

        try {
            // 获取分类列表
            response.setCategories(getCategories());

            // 获取文章列表
            response.setArticles(getArticles(queryRequest));

            log.info("首页数据获取成功");
            return response;
        } catch (Exception e) {
            log.error("获取首页数据失败", e);
            throw new RuntimeException("获取首页数据失败：" + e.getMessage());
        }
    }

    @Override
    public List<HomePageResponse.CategoryInfo> getCategories() {
        log.info("获取分类列表");
        try {
            return categoryMapper.selectHomeCategoryList();
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            throw new RuntimeException("获取分类列表失败：" + e.getMessage());
        }
    }

    @Override
    public HomePageResponse.ArticleListData getArticles(HomePageQueryRequest queryRequest) {
        return getArticles(queryRequest, null);
    }

    @Override
    public HomePageResponse.ArticleListData getArticles(HomePageQueryRequest queryRequest, Long currentUserId) {
        log.info("获取文章列表: {}, 用户ID: {}", queryRequest, currentUserId);
        
        try {
            // 创建分页对象
            Page<Map<String, Object>> page = new Page<>(
                queryRequest.getCurrent(),
                queryRequest.getSize()
            );

            // 查询文章列表
            IPage<Map<String, Object>> pageResult = articleMapper.selectHomeArticlePage(page, queryRequest);

            // 转换为ArticleInfo对象
            List<HomePageResponse.ArticleInfo> articles = new ArrayList<>();
            for (Map<String, Object> map : pageResult.getRecords()) {
                HomePageResponse.ArticleInfo article = convertMapToArticleInfo(map);
                articles.add(article);
            }

            // 如果用户已登录，批量查询用户交互状态
            if (currentUserId != null && !articles.isEmpty()) {
                enrichArticlesWithUserInteractionStatus(articles, currentUserId);
            }

            // 构建响应数据
            HomePageResponse.ArticleListData articleListData = new HomePageResponse.ArticleListData();
            articleListData.setRecords(articles);
            articleListData.setTotal(pageResult.getTotal());
            articleListData.setCurrent(pageResult.getCurrent());
            articleListData.setSize(pageResult.getSize());
            articleListData.setPages(pageResult.getPages());
            articleListData.setHasNext(pageResult.getCurrent() < pageResult.getPages());
            
            log.info("文章列表获取成功，共{}条记录", pageResult.getTotal());
            return articleListData;
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            throw new RuntimeException("获取文章列表失败：" + e.getMessage());
        }
    }



    /**
     * 将Map转换为ArticleInfo对象，并过滤敏感数据
     */
    private HomePageResponse.ArticleInfo convertMapToArticleInfo(Map<String, Object> map) {
        HomePageResponse.ArticleInfo article = new HomePageResponse.ArticleInfo();

        article.setId(getLongValue(map, "id"));
        article.setTitle(getStringValue(map, "title"));
        article.setSummary(getStringValue(map, "summary"));
        article.setCoverImage(getStringValue(map, "coverImage"));
        
        // 作者信息 - 过滤敏感数据
        article.setAuthorId(getLongValue(map, "authorId"));
        // 不返回真实用户名，只返回昵称
        article.setAuthorName(null); // 敏感数据，不返回给前端
        article.setAuthorNickName(getStringValue(map, "authorNickName"));
        article.setAuthorAvatar(getStringValue(map, "authorAvatar"));
        
        article.setCategoryId(getLongValue(map, "categoryId"));
        article.setCategoryName(getStringValue(map, "categoryName"));
        article.setViewCount(getIntegerValue(map, "viewCount"));
        article.setLikeCount(getIntegerValue(map, "likeCount"));
        article.setCommentCount(getIntegerValue(map, "commentCount"));
        article.setCollectCount(getIntegerValue(map, "collectCount"));
        article.setIsTop(getBooleanValue(map, "isTop"));
        article.setIsOriginal(getBooleanValue(map, "isOriginal"));
        article.setPublishTime((LocalDateTime) map.get("publishTime"));
        article.setReadingTime(getIntegerValue(map, "readingTime"));

        // 处理标签（过滤敏感信息）
        article.setTags(processArticleTagsFiltered(getLongValue(map, "id")));
        
        // 初始化交互状态为false，后续会通过批量查询更新
        article.setIsLiked(false);
        article.setIsCollected(false);

        return article;
    }

    /**
     * 批量为文章列表补充用户交互状态
     */
    private void enrichArticlesWithUserInteractionStatus(List<HomePageResponse.ArticleInfo> articles, Long userId) {
        if (articles == null || articles.isEmpty() || userId == null) {
            return;
        }

        try {
            // 提取文章ID列表
            List<Long> articleIds = articles.stream()
                .map(HomePageResponse.ArticleInfo::getId)
                .filter(id -> id != null)
                .toList();

            if (articleIds.isEmpty()) {
                return;
            }

            // 批量查询用户点赞状态
            List<Long> likedArticleIds = articleMapper.batchCheckUserLike(userId, articleIds);
            // 批量查询用户收藏状态
            List<Long> collectedArticleIds = articleMapper.batchCheckUserCollect(userId, articleIds);

            // 将查询结果转换为Set以提高查找效率
            java.util.Set<Long> likedSet = new java.util.HashSet<>(likedArticleIds);
            java.util.Set<Long> collectedSet = new java.util.HashSet<>(collectedArticleIds);

            // 为每篇文章设置交互状态
            for (HomePageResponse.ArticleInfo article : articles) {
                if (article.getId() != null) {
                    article.setIsLiked(likedSet.contains(article.getId()));
                    article.setIsCollected(collectedSet.contains(article.getId()));
                }
            }

            log.debug("用户交互状态批量查询完成，用户ID: {}, 文章数量: {}, 已点赞: {}, 已收藏: {}", 
                userId, articles.size(), likedArticleIds.size(), collectedArticleIds.size());
        } catch (Exception e) {
            log.error("批量查询用户交互状态失败: userId={}", userId, e);
            // 出错时设置默认值
            for (HomePageResponse.ArticleInfo article : articles) {
                article.setIsLiked(false);
                article.setIsCollected(false);
            }
        }
    }

    /**
     * 处理文章标签，从关联表获取标签详细信息（过滤版本）
     */
    private List<HomePageResponse.TagInfo> processArticleTagsFiltered(Long articleId) {
        try {
            if (articleId == null) {
                return new ArrayList<>();
            }
            
            // 从关联表获取标签信息
            List<ArticleTag> articleTags = articleTagRelationService.getTagsByArticleId(articleId);
            
            if (articleTags == null || articleTags.isEmpty()) {
                return new ArrayList<>();
            }
            
            List<HomePageResponse.TagInfo> tagInfoList = new ArrayList<>();
            for (ArticleTag tag : articleTags) {
                HomePageResponse.TagInfo tagInfo = new HomePageResponse.TagInfo();
                tagInfo.setId(tag.getId());
                tagInfo.setName(tag.getName());
                tagInfo.setColor(tag.getColor());
                // 过滤敏感信息 - 前端不需要看到这些管理信息
                tagInfo.setDescription(null); // 不返回标签描述（可能包含管理信息）
                tagInfo.setIcon(tag.getIcon());
                tagInfo.setUseCount(null); // 不返回使用次数（管理信息）
                tagInfoList.add(tagInfo);
            }
            
            return tagInfoList;
        } catch (Exception e) {
            log.error("处理文章标签失败: articleId={}", articleId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 处理文章标签，从关联表获取标签详细信息（完整版本，仅内部使用）
     */
    private List<HomePageResponse.TagInfo> processArticleTags(Long articleId) {
        try {
            if (articleId == null) {
                return new ArrayList<>();
            }
            
            // 从关联表获取标签信息
            List<ArticleTag> articleTags = articleTagRelationService.getTagsByArticleId(articleId);
            
            if (articleTags == null || articleTags.isEmpty()) {
                return new ArrayList<>();
            }
            
            List<HomePageResponse.TagInfo> tagInfoList = new ArrayList<>();
            for (ArticleTag tag : articleTags) {
                HomePageResponse.TagInfo tagInfo = new HomePageResponse.TagInfo();
                tagInfo.setId(tag.getId());
                tagInfo.setName(tag.getName());
                tagInfo.setColor(tag.getColor());
                tagInfo.setDescription(tag.getDescription());
                tagInfo.setIcon(tag.getIcon());
                tagInfo.setUseCount(tag.getUseCount());
                tagInfoList.add(tagInfo);
            }
            
            return tagInfoList;
        } catch (Exception e) {
            log.error("处理文章标签失败: articleId={}", articleId, e);
            return new ArrayList<>();
        }
    }

    private String getStringValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value != null ? value.toString() : null;
    }

    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Long) return (Long) value;
        if (value instanceof Integer) return ((Integer) value).longValue();
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private Integer getIntegerValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Integer) return (Integer) value;
        if (value instanceof Long) return ((Long) value).intValue();
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private Boolean getBooleanValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return false;
        if (value instanceof Boolean) return (Boolean) value;
        if (value instanceof Integer) return ((Integer) value) == 1;
        if (value instanceof Long) return ((Long) value) == 1L;
        return Boolean.parseBoolean(value.toString());
    }


}
